package com.example.jiangqiangwei.mypermission1608demo;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 6.0以上读写sdcard
 */
public class SDCardActivity extends AppCompatActivity {

    private TextView txtShow;
    private static final int WRITE_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sdcard);
        txtShow = (TextView) findViewById(R.id.txt_show);
    }

    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.bt_writesdcard:
                if (SDCardUtils.isSDCardEnable()) {
                    Toast.makeText(this, "sdcard有", Toast.LENGTH_SHORT).show();
                    //检查sdcard权限是否被申请
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            == PackageManager.PERMISSION_GRANTED) {
                        //操作sdcard
                        addData();
                    } else {

                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_CODE);
                    }
                } else {
                    Toast.makeText(this, "sdcard没有", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.bt_readsdcrad:
                readData();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == WRITE_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            addData();
        } else {
            Toast.makeText(this, "申请权限", Toast.LENGTH_SHORT).show();
        }
    }

    private void readData() {
        byte[] oks = SDCardUtils.readFileFromSDCard(SDCardUtils.getSDCardPath(), "ok");
        if (oks != null && oks.length > 0) {
            txtShow.setText(new String(oks));
        }
    }


    //写入sdcard
    private void addData() {
        try {
            //1.保存路径2.文件名称3.保存的具体内容
            boolean b = SDCardUtils.saveFileToSDCard(SDCardUtils.getSDCardPath(), "ok", "保存的内容");
            if (b) {
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
